package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.Result;
import com.heima.domain.dto.RegionDto;
import com.heima.domain.po.Region;
import com.heima.domain.vo.RegionVo;
import com.heima.mapper.RegionMapper;
import com.heima.service.RegionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {

    @Autowired
    private RegionMapper regionMapper;
    /**
     * 分页查询区域
     *
     * @param pageIndex
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Result getByPage(Integer pageIndex, Integer pageSize, String name) {
        Page<RegionVo> page = new Page<>(pageIndex,pageSize);
        Page<RegionVo> result = regionMapper.getByPage(page,name,null);
        Result of = Result.of(result);
        return of;
    }

    /**
     * 新增区域
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean addRegion(RegionDto dto) {
        Region region = new Region();
        region.setName(dto.getRegionName());
        region.setRemark(dto.getRemark());
        try {
            regionMapper.insert(region);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 修改区域
     *
     * @param regionId
     * @return
     */
    @Override
    public Boolean updateRegion(Long regionId,RegionDto dto) {
        Region region = new Region();
        BeanUtils.copyProperties(dto,region);
        region.setName(dto.getRegionName());
        try {
            lambdaUpdate().eq(regionId != null,Region::getId,regionId).update(region);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除区域
     *
     * @param regionId
     * @return
     */
    @Override
    public Boolean deleteRegion(Long regionId) {
        try {
            lambdaUpdate().eq(regionId != null,Region::getId,regionId).remove();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
